import type { MaybeRefOrGetter } from 'vue'
import { modelConfigApi } from '@/api'

export interface Tree {
  id: number
  parentId: number
  pointName: string
  children?: Tree[] | null
}

export function usePointTree(
  modelType: MaybeRefOrGetter<string>,
) {
  const { vLoading, withLoading } = useDefineLoading()
  const treeData = shallowRef<any[]>([])
  const getTreeData = async () => {
    try {
      treeData.value = []
      const { data } = await withLoading(
        modelConfigApi.getPointTreeByModel,
      )(toValue(modelType))
      treeData.value = data || []
    }
    catch (e) {}
  }

  watchEffect(() => {
    getTreeData()
  })

  return {
    modelType,
    treeData,
    vLoading,
    getTreeData,
  }
}

export function useTreeFilter(
  key: string = 'label',
  callback?: (val: string) => any,
) {
  const filterTextInput = ref<string>('')

  const filterNode = (value: string, data: any) => {
    if (!value)
      return true
    return data[key].includes(value)
  }

  watch(
    () => filterTextInput.value,
    (val: string) => {
      callback?.(val)
    },
  )
  return {
    filterTextInput,

    filterNode,
  }
}
